'''
Created on 22 mai 2009

@author: tmeedendorp
'''

from manager.bean_store      import *
from util.file_util import *
from reader.file_reader import FileLineReader
from reader.pdf_reader import PdfLineReader
import time
import webbrowser


class ProcessFileManager:
    def __init__(self):
        self.lineComputorList = []
        self.documentReaderList = []
    
    
    def registerDocument(self, document):
        if document.lower().endswith("txt"):
            self.documentReaderList.append(FileLineReader(document))
        elif document.lower().endswith("pdf"):
            self.documentReaderList.append(PdfLineReader(document))
        else:
            print "document \"" + document + "\" is not a text file nor a pdf file."
            
    def registerComputor(self, computor):
        self.lineComputorList.append(computor)
        
    def clearDocuments(self):
        self.documentReaderList[:] = []
        
    def clearComputors(self):
        self.lineComputorList[:] = []
        
    def writeHTMLHeader(self, htmlFile, document):
        htmlFile.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n")
        htmlFile.write("<html lang=\"fr\" xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\">\n")
        htmlFile.write("\t<head>\n")
        htmlFile.write("\t\t<title>PyMining</title>\n")
        htmlFile.write("\t\t<meta content=\"text/html; charset=ISO8859-1\" http-equiv=\"Content-Type\"/>\n")
      
        appendFileContent(getBean("configurationManager").getConfigDir()+"htmlHeader.tpl", htmlFile)
        htmlFile.write("\t</head>\n")
        htmlFile.write("\t<body>\n")
        htmlFile.write("\t\t<h1>Statistiques du fichier \""+document+"\"</h1>\n")
        
    def writeReportContent(self, htmlFile, reportFile):
        htmlFile.write("\t\t<div class=\"rapport_content\">\n")
        lineNumber = 1
        reportFile.jumpToBegining()
        while 1:
            line = reportFile.readNextLine()
            if line == None:
                    break
            htmlFile.write("\t\t\t<a name=\"line_anchor"+str(lineNumber)+"\"/><div style=\"display:none\" id=\"line_"+str(lineNumber)+"\">"+line.strip('').replace("&", "&amp;")+"</div>\n")
            lineNumber+=1
        htmlFile.write("\t\t</div>\n")
    
    def writeHTMLFooter(self, htmlFile):
        htmlFile.write("</body></html>\n")
    
    
    def processDocument(self, reportFileReader):  
        reportFileReader.open()
        htmlFile = None
        try:
            lineNumber = 1
            while 1:
                line = reportFileReader.readNextLine()
                if line == None:
                    break
                for word in line.split():
                    word = word.lower().strip(' \t\n,.()')
                    if len(word) > 2:
                        for lineComputor in self.lineComputorList:
                            lineComputor.processWord(word, lineNumber)
                lineNumber+=1
            htmlFilename = reportFileReader.document+".html"
            print("Generating HTML File \""+ htmlFilename + "\"")
            htmlFile = open(htmlFilename, "w")
            self.writeHTMLHeader(htmlFile,reportFileReader.document)
            
            # write computor results
            for lineComputor in self.lineComputorList:
                htmlFile.write("\t\t\t<h2>Resultats pour l'extension \""+lineComputor.name+"\"</h2>\n")
                lineComputor.writeHTMLResult(htmlFile)
            
            self.writeReportContent(htmlFile, reportFileReader)
            self.writeHTMLFooter(htmlFile)
            print("HTML File generated")
            webbrowser.open("file://" + htmlFilename)

        except IOError :
            print IOError
            print "IO Error"

    
        
    def processDocuments(self):
        for documentReader in self.documentReaderList:
            print("Processing document \""+documentReader.document+"\"")
            startTime = time.clock()
            self.processDocument(documentReader)
            endTime = time.clock()
            print("Finished processing document \""+documentReader.document+"\" in "+ str(endTime - startTime) + "seconds")
